﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Management;
using System.Collections;

namespace WMIUSB
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //file creation
                FileStream fs = null;
                using (fs = File.Create("USBDevices.txt"))
                    fs.Close();


                //wmi connection
                ManagementScope scope = new ManagementScope("\\root\\CIMV2");
                scope.Connect();
                //get usb devices with a VID/PID
                ObjectQuery usbQuery = new ObjectQuery("select * from Win32_PnPEntity where DeviceID like \"%USB%\" and DeviceID like \"%VID%\"");
                ManagementObjectSearcher usbSearcher = new ManagementObjectSearcher(scope, usbQuery);
			
                using (StreamWriter sw = new StreamWriter("USBDevices.txt", true))
                {
                    sw.WriteLine("USB Devices attached", true);
                    sw.Close();
                }
                //loop through all devices
                foreach (ManagementObject queryObj in usbSearcher.Get())
                {
                    string strDeviceID = queryObj["DeviceID"].ToString();
                    //split the DeviceID on \
                    string[] arrDeviceID = strDeviceID.Split('\\');
                    //now spilt on the &
                    string[] vidpid = arrDeviceID[1].Split('&');
                    //remove the VID_ part 
                    string vid = vidpid[0].Remove(0,4);
                    //remove the PID_part 
                    string pid = vidpid[1].Remove(0,4);
					//write to the console and to a file
                    Console.WriteLine("VID {0} PID {1}",vid,pid);
                    using (StreamWriter sw = new StreamWriter("USBDevices.txt", true))
                    {
                        sw.WriteLine("VID = " + vid + " PID = " + pid, true);
                        sw.Close();
                    }
                }

            
            }
            catch (ManagementException err)
            {
                Console.WriteLine("An error occured while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                Console.WriteLine("Connection error " + "(user name or password might be incorrect): " + unauthorizedErr.Message);
            }
        }
    }
}
